//维修计划
import React, { Component } from 'react';
import { Table, Button, Form, Card, Tabs, Modal, DatePicker, Select } from 'antd';
import '@/assets/css/settings';
import * as Utils from "../../utils_yyr/action";
import BasicForm from "../../components_yyr/common/basicForm";
import { withRouter } from 'react-router-dom';
import BasicDrawers from "../../components_yyr/common/basicDrawers";
import { FileDown } from "../../components_yyr/commponent/File";
import Paging from "../../components_yyr/commponent/Paging";
import BasicConfirm from "../../components_yyr/common/basicConfirm";
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
import moment from 'moment';
const { TabPane } = Tabs;
const { Option } = Select
const nowDate = Utils.getNowDate()
class App extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [], //数据源
		drawerVisible: false,//新增修改抽屉的显示与隐藏
		chooseData: {},
		drawerTitle: '',
		total: 0,
		formValues: {},
		cityData: [],
		mainFactoryList: [],
		selectedData: [],
		selectedKeys: [],
		isModalVisible: false,
		wxz: [],
		selectedDateTime: moment(new Date(), "YYYY-MM-DD"),
		visibleDispatch: false,
		UserList: []
	};
	componentDidMount() {
		this.fetch({
			pageNum: 1,
			pageSize: 10,
			userId: localStorage.getItem('userId'),
			typeId: 2,
			isApp: 0
		});
		// this.getInfo();
		this.wxz()
		this.queryPageUser()
	}
	//初始化加载数据
	fetch = (data) => {
		console.log(data)
		let str = ''
		for (var key in data) {
			if (data[key] || data[key] == 0) {
				str += `&${key}=${data[key]}`
			}
		}
		this.setState({ loading: true })
		this.get(euqApplicationName + '/equipmentRepairPlan/findEquipmentRepairPlan?' + str).then(res => {
			this.setState({
				loading: false,
				dataSource: res.data,
				total: res.total,
				formValues: data
			});
		})
	}
	wxz = () => {//维修组
		this.get(euqApplicationName + '/parameter_setting_public/queryTeamPageList?type=维修').then(res => {
			this.setState({
				wxz: res.data,
			});
		})
	};
	//   用户查询
	queryPageUser = () => {
		this.get(lotAuth2 + '/user/queryPageUser').then(res => {
			this.setState({
				UserList: res.data.data
			});
		})
	}

	//表单查询
	filterSubmit = (values) => {
		console.log("表单查询=====", values)
		if (values.startTime_endTime && values.startTime_endTime.length == 2) {
			values.startTime = Utils.getDate(values.startTime_endTime[0])
			values.endTime = Utils.getDate(values.startTime_endTime[1])
		}
		values.pageNum = this.state.formValues.pageNum;
		values.pageSize = this.state.formValues.pageSize;
		values.userId = localStorage.getItem('userId')
		values.typeId = 2
		values.isApp = 0
		this.fetch(values);
	};

	// 表格删除
	// 表格删除
	handleConfirm = (value, api, chooseData) => {
		console.log(this.state.selectedData)
		let str = ''
		for (var item of this.state.selectedData) {
			str += item.id + ','
		}
		this.get(`${euqApplicationName}/equipmentRepairPlan/deleteEquipmentRepairPlan?ids=${str.slice(0, str.length - 1)}`).then(res => {
			this.success();
			this.fetch({ ...this.state.formValues });
			this.setState({ selectedKeys: [], selectedData: [] })
		});
	};

	formList = () => {
		const formList = [

			{
				type: "SELECT", label: "计划状态", field: "planStatus", name: 'value',
				// 处理状态1.待审核 2.审核中 3.待维修 4.维修中 5.待验证 6.已完成
				list: [{ id: 0, value: '待执行' }, { id: 1, value: '执行中' }, { id: 2, value: '已完成' },],
				valueField: 'id'
			},
			{ type: "TIMEFRAME", label: "计划时间", field: "startTime_endTime", },
			{
				type: "SELECT", label: "维修组", field: "maintainTeam", name: 'name',
				list: this.state.wxz, valueField: 'name'
			},
		]
		return formList;
	};
	drawerFormList = data => {
		const { mainFactoryList } = this.state;
		const drawerFormList = [
			{ type: "TITLE", label: "添加计划" },
			{ type: "BOTTOM", label: "选择设备", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice, },
			{ type: "TABLE", label: "", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },

			{ type: 'TITLE', label: '维修信息' },
			{ type: "DATE", label: "计划执行时间", field: "harborOneHundredPrice", initialValue: data.harborOneHundredPrice, list: mainFactoryList, required: true },
			{ type: "INPUT", label: "提醒时间", field: "route", initialValue: data.route },
			{ type: "SELECT", label: "维修类别", field: "gzlevel", initialValue: data.gzlevel, name: 'value', valueField: 'value', list: mainFactoryList.gzlevel, },
			{ type: "SELECT", label: "紧急程度", field: "harborTwoHundredPrice", initialValue: data.harborTwoHundredPrice, name: 'value', valueField: 'value', list: mainFactoryList.harborTwoHundredPrice },
			{ type: "SELECT", label: "维修组", field: "harborOneTonPrice", initialValue: data.harborOneTonPrice, name: 'value', valueField: 'value', list: mainFactoryList.harborOneTonPrice },
			{ type: "SELECT", label: "维修人员", field: "doorMinimumPrice", initialValue: data.doorMinimumPrice, name: 'value', valueField: 'value', list: mainFactoryList.doorMinimumPrice },
			{ type: "INPUT", label: "工作天数", field: "uniqueAddress", initialValue: data.uniqueAddress, name: 'value', valueField: 'value', list: mainFactoryList },
			{ type: "INPUT", label: "人均工时/天", field: "doorOneHundredPrice", initialValue: data.doorOneHundredPrice },
			{ type: "SELECT", label: "外委单位", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "INPUT", label: "外协工时", field: "harborOneHundredPrice", initialValue: data.harborOneHundredPrice },
			{ type: "TEXTAREA", label: "描述", field: "remarks", initialValue: data.remarks }
		];
		return drawerFormList;
	};

	// 提交modal
	handleSubmit = data => {
		const { dataSource, chooseData } = this.state;
		let key = chooseData.key;
		let newDataSource = dataSource;
		let index = newDataSource.findIndex((value) => value.key == key);
		if (key) {
			console.log("******修改******")
			for (let j of newDataSource) {
				if (j.key == key) {
					newDataSource[index] = { ...newDataSource[index], ...data }
				}
			}
		} else {
			console.log("******添加******")
			newDataSource.push(data);
		}
		this.setState({
			dataSource: newDataSource,
		})
		this.onClose();


		// 注释
		// const id = this.state.chooseData && this.state.chooseData.id;
		// if (id) {
		// 	data = Object.assign({}, data, { id: id });
		// 	data.updateId = localStorage.getItem('userId');
		// } else {
		// 	data.createId = localStorage.getItem('userId');
		// }
		// this.post('/airCargo/addAirCargo', { data }).then(res => {
		// 	this.success();
		// 	this.fetch({ ...this.state.formValues });
		// 	this.onClose();
		// })

	};

	// 打开modal，判断是修改还是新增 0新增 1修改
	handleModal = (type, data) => {
		let { selectedData } = this.state
		if (selectedData.length !== 1) {
			Utils.openNotification('warning', '请选择一个计划进行执行！')
			return
		}
		if (selectedData[0].status !== 0) {
			Utils.openNotification('warning', '计划状态不符，不能执行！')
			return
		}
		this.props.history.push('/PlayMaintenancePlan/' + selectedData[0].planId)
		// let obj = selectedData[0]
		// obj.userId = localStorage.getItem('userId')
		// let equipmentRepairWorkAddDTOList = []
		// if(obj.wxUserName && obj.maintainPersons){
		// 	let arrName = obj.wxUserName.split(',')
		// 	let arrId = obj.maintainPersons.split(',')
		// 	for(var key in arrId){
		// 		let o = {}
		// 		o.personId = arrId[key]
		// 		o.personName = arrName[key]
		// 		o.planId = obj.planId
		// 		if(key==0){
		// 			o.perType = 1
		// 		}else{
		// 			o.perType = 0
		// 		}
		// 		equipmentRepairWorkAddDTOList.push(o)
		// 	}
		// }else{
		// 	equipmentRepairWorkAddDTOList.push({
		// 		personId:localStorage.getItem('userId'),
		// 		personName:localStorage.getItem('userName'),
		// 		perType:1,
		// 		planId:obj.planId
		// 	})
		// }
		// obj.equipmentRepairWorkAddDTOList = equipmentRepairWorkAddDTOList
		// console.log(obj)
		// this.post(euqApplicationName + '/equipmentRepairPlan/implementationPlan',{data:obj}).then(res => {
		// 	console.log(res)
		// 	let id = res.data
		// 	this.props.history.push('/PlayMaintenancePlan/'+id)
		// })
	};

	onClose = () => {
		this.setState({
			drawerVisible: false,
			chooseData: {}
		});
		this.modalRef.props.form.resetFields();
	}

	// 选择时间
	dateTimeChange = (date, dateString) => {
		this.setState({
			selectedDateTime: date
		});
	};

	// 打开计划
	showModal = (type, data) => {
		const { selectedData } = this.state;
		if (selectedData.length >= 1) {
			for (var item of selectedData) {
				if (item.status !== 0) {
					Utils.openNotification("warning", '单据状态不符,待执行计划才能调整时间！')
					return;
				}
			}
			this.setState({
				isModalVisible: true,
				selectedDateTime: moment(nowDate, "YYYY-MM-DD")
			});
		} else {
			Utils.openNotification('warning', '请选择一条计划')

		}
	};

	onOkModal = () => {
		const { selectedData, selectedDateTime } = this.state;
		for (var item of selectedData) {
			item.planExeTime = Utils.getDate(selectedDateTime)
			item.id = item.planId
		}
		console.log(selectedData)
		this.post(`${euqApplicationName}/equipmentRepairPlan/adjustPlanningTime`, { data: selectedData }).then(res => {
			this.success();
			this.fetch({ ...this.state.formValues });
			this.hideModal()
			this.setState({ selectedKeys: [], selectedData: [] })
		});
	};

	hideModal = () => {
		this.setState({
			isModalVisible: false,
		});
	};

	test = (event) => {
		console.log(event)
		this.props.form.resetFields('majorStaffs')
		if (event == undefined) {
			this.queryPageUser()
			return
		} else {
			this.props.form.resetFields('majorStaffs')
			const { wxz } = this.state
			wxz.forEach((item) => {
				return item.id == event && this.setState({ UserList: item.userIdList })
			})
		}

	}
	handleOk = () => {
		this.props.form.validateFields(['majorStaffs', 'repairTeamId',], (err, values) => {
			if (!err) {
				if (values['majorStaffs'] || values['repairTeamId']) {
					let selectedData = this.state.selectedData
					let selectedKeys = []
					for (var item of selectedData) {
						selectedKeys.push(item.planId)
					}
					values.ids = selectedKeys
					values.userId = localStorage.getItem('userId')
					console.log(values)
					let equipmentRepairWorkAddDTOList = []
					values['majorStaffs'].forEach(item => {
						for (var itemss of this.state.UserList) {
							if (itemss.userId == item) {
								equipmentRepairWorkAddDTOList.push({
									personId: item,
									personName: itemss.userName
								})
							}
						}
					})
					for (let i in equipmentRepairWorkAddDTOList) {
						if (i == 0) {
							equipmentRepairWorkAddDTOList[i].perType = 0
						} else {
							equipmentRepairWorkAddDTOList[i].perType = 1
						}
					}
					values.equipmentRepairWorkAddDTOList = equipmentRepairWorkAddDTOList
					this.post(euqApplicationName + '/equipmentRepairPlan/batchDispatch', { data: values }).then(res => {
						this.success()
						this.handleCancel()
					})
				} else {
					Utils.openNotification('warning', '请在班组和维修人员中至少选择一项派工！')
				}
			}
		})
	}
	handleCancel = () => {
		this.setState({ visibleDispatch: false, selectedKeys: [], selectedData: [] })
		this.fetch({ ...this.state.formValues })
		this.props.form.resetFields();
	}
	dispatch = () => {
		let data = this.state.selectedData
		if (data.length === 0) {
			Utils.openNotification("warning", '请选择要派工单据!')
			return;
		}
		for (var item of data) {
			if (item.status !== 0) {
				Utils.openNotification("warning", '待执行的单据才能派工！')
				return;
			}
		}
		this.setState({
			visibleDispatch: true
		})
	}
	render() {
		const columns = [
			{
				title: '详细', width: 70, dataIndex: 'detail',
				render: (text, record) => { return record.status === 0 ? <span><a href onClick={() => this.props.history.push('/AddPlans/' + record.planId)}>修改</a></span> : record.status === 1 || record.status === 2 ? <span><a href onClick={() => this.props.history.push('/DetailsPlan/' + record.planId)}>详情</a></span> : '' }
			},
			{ title: '计划状态', width: 100, dataIndex: 'status', render: (text) => { return text === 0 ? '待执行' : text === 1 ? '执行中' : text === 2 ? '已完成' : '' } },

			{ title: '设备编号', width: 150, dataIndex: 'equCode', },
			{ title: '设备名称', width: 100, dataIndex: 'equName', },
			{ title: '部门', width: 150, dataIndex: 'deptName', },
			{ title: '计划执行时间', width: 150, dataIndex: 'planExeTime', },
			{ title: '紧急程度', width: 150, dataIndex: 'urgency', },
			{ title: '维修类型', width: 150, dataIndex: 'maintenanceCategory', },//?
			{ title: '维修组', width: 150, dataIndex: 'teamName', },
			{ title: '维修人员', width: 150, dataIndex: 'wxUserName', },
			{ title: '计划(人*时*天)', width: 150, dataIndex: 'plan', },
			{ title: '总计划工时', width: 150, dataIndex: 'totalWorkHours', },
			{ title: '外协工时', width: 150, dataIndex: 'outsourceHours', },
			{ title: '计划描述', width: 100, dataIndex: 'remarks', },
			// {
			// 	title: '操作', width: 150,
			// 	render: (text, record) => {
			// 		return <span><a href onClick={() => this.handleModal(1, record)}>修改</a></span>
			// 	}
			// }
		];
		const { chooseData, drawerVisible, drawerTitle, dataSource, loading, total, formValues, selectedData, selectedKeys, selectedDateTime, wxz, UserList } = this.state;

		const drawerProps = {
			onRef: (ref) => this.modalRef = ref, visible: drawerVisible, width: 700, drawerFormList: this.drawerFormList(chooseData),
			submit: this.handleSubmit, onClose: this.onClose, title: drawerTitle
		}
		const { getFieldDecorator } = this.props.form
		//选择框
		const rowSelection = {
			selectedRowKeys: selectedKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedData: selectedRows,
					selectedKeys: selectedRowKeys
				})
			},
			getCheckboxProps: record => ({
				disabled: record.name === 'Disabled User',
				name: record.name
			})
		};

		return (
			<div className="shadow-radius">
				<Card><BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={(ref) => this.child = ref} /></Card>

				<Tabs tabBarExtraContent={
					<div className="buttonList">
						<Button icon="plus" onClick={() => this.props.history.push('/AddPlans/new')} type="primary"> 添加计划</Button>
						{/* <Button icon="plus" onClick={() => this.handleModal(0, {})} type="primary"> 添加计划</Button> */}
						<Button icon="plus" onClick={() => this.showModal(0, {})} type="primary"> 调整计划执行时间</Button>
						<Button icon="form" onClick={() => this.handleModal(0, {})} type="primary"> 执行计划</Button>
						<Button icon="plus" onClick={() => { this.dispatch() }} type="primary"> 派工 </Button>
						{/* <Button icon="apartment" onClick={() => this.handleModal(0, {})} type="primary"> 派工</Button> */}
						{/* <Button icon="delete" onClick={() => this.handleModal(0, {})} type="primary"> 删除</Button> */}
						<BasicConfirm title="确认删除?" api={1} icon="delete" button={true} buttonName="删除" data={selectedData} handleConfirm={this.handleConfirm} />
						{/* <FileDown fileName='设备台账模板' buttonName='模板下载' apiPath='/airCargo/carrierPriceExcel'/> */}
						<FileDown fileName='维修计划清单' buttonName='导出' method='post' apiPath={euqApplicationName + '/equipmentRepairPlan/exportEquipmentRepairPlanListExcel'} data={{ ...this.state.formValues, ids: selectedData.map(item => item.planId), typeId: [2], statusIds: this.state.formValues.statusIds ? [this.state.formValues.statusIds] : [] }} />
					</div>
				}>
					<TabPane tab='维修计划' key='1'>
						<Table columns={columns} rowSelection={rowSelection} rowKey={(record, index) => record.id} dataSource={dataSource} pagination={false} loading={loading} scroll={{ x: 1300 }} />
						<Paging total={total} formValues={formValues} fetch={(pager) => this.fetch(pager)} />
					</TabPane>
				</Tabs>

				<Modal title="调整计划执行时间" visible={this.state.isModalVisible} onOk={this.onOkModal} onCancel={this.hideModal} okText="确认" cancelText="取消">
					<Form>
						<Form.Item >
							时间调整为：<DatePicker style={{ width: '80%' }} onChange={this.dateTimeChange} value={selectedDateTime} />
						</Form.Item>
					</Form>

				</Modal>


				<BasicDrawers	{...drawerProps} />
				<Modal
					title="派工"
					visible={this.state.visibleDispatch}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
					okText="确认"
					cancelText="取消"
				>
					<Form>
						<Form.Item label="维修组">
							{getFieldDecorator('repairTeamId', { rules: [{ required: true, message: '请选择维修组' }] })(<Select allowClear placeholder='请输入维修组' onChange={this.test}>
								{wxz.map(item => <Option value={item.id}>{item.name}</Option>)}
							</Select>)}
						</Form.Item>
						<Form.Item label="维修人员">
							{getFieldDecorator('majorStaffs', { rules: [{ required: true, message: '请选择维修人员' }] })(<Select mode="multiple" allowClear placeholder='请输入维修人员'>
								{UserList.map(item => <Option value={item.userId}>{item.userName}</Option>)}
							</Select>)}
						</Form.Item>
					</Form>
				</Modal>
			</div>
		);
	}
}
export default Form.create()(withRouter(App));